#ifndef _COM_HPP_
#define _COM_HPP_

#include <iostream>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <cerrno>
#include <string.h>
#include <cstdio>
#include <unistd.h>

#define PATHNAME "."
#define PROJ_ID 0x24
#define MAX_SIZE 2048



// 生成key值
int getKey()
{
    key_t k = ftok(PATHNAME, PROJ_ID);
    if (k < 0)
    {
        std::cerr << "getKey: " << errno << ": " << strerror(errno) << std::endl;
        exit(1);
    }
    return k;
}

// 创建共享内存，一定是新的
int creatSHM(int key)
{
    int shmid = shmget(key, MAX_SIZE, IPC_CREAT | IPC_EXCL | 0600);
    if (shmid < 0)
    {
        std::cerr << "creatSHM: " << errno << ": " << strerror(errno) << std::endl;
        exit(2);
    }
    return shmid;
}

// 获取共享内存
int getSHM(int key)
{
    int shmid = shmget(key, MAX_SIZE, IPC_CREAT);
    if (shmid < 0)
    {
        std::cerr << "getSHM: " << errno << ": " << strerror(errno) << std::endl;
        exit(3);
    }
    return shmid;
}

// 挂接
void *attachSHM(int shmid)
{
    void *start = shmat(shmid, nullptr, 0);
    if ((long long)start == -1)
    {
        std::cerr << "attachSHM: " << errno << ": " << strerror(errno) << std::endl;
        exit(4);
    }

    return start;
}

//去关联
void detachSHM(void* start)
{
    int n = shmdt(start);
    if(n<0)
    {
        std::cerr << "detatchSHM: " << errno << ": " << strerror(errno) << std::endl;
        exit(5);
    }
}

// 删除共享内存
void delSHM(int shmid)
{
    int n = shmctl(shmid, IPC_RMID, 0);
    if (n < 0)
    {
        std::cerr << "delSHM: " << errno << ": " << strerror(errno) << std::endl;
    }
}

#endif


